@{
    ViewData["Title"] = "知识库管理";
    Layout = "_Layout";
}

<div class="layui-container-fluid">
    <div class="layui-row layui-col-space15">
        <div class="layui-col-md12">
            <div class="layui-card">
                <div class="layui-card-header">
                    <h3>知识库管理</h3>
                </div>
                <div class="layui-card-body">
                    <!-- 工具栏 -->
                    <div class="layui-btn-container" style="margin-bottom: 20px;">
                        <button type="button" class="layui-btn layui-btn-normal" id="uploadButton">
                            <i class="fas fa-upload"></i> 上传文档
                        </button>
                        <button type="button" class="layui-btn layui-btn-warm" id="refreshButton">
                            <i class="fas fa-refresh"></i> 刷新
                        </button>
                        <button type="button" class="layui-btn layui-btn-danger" id="batchDeleteButton">
                            <i class="fas fa-trash"></i> 批量删除
                        </button>
                    </div>

                    <!-- 搜索区域 -->
                    <div class="layui-row layui-col-space10" style="margin-bottom: 20px;">
                        <div class="layui-col-md8">
                            <input type="text" class="layui-input" id="searchInput" placeholder="搜索文档名称、类型或状态...">
                        </div>
                        <div class="layui-col-md4">
                            <button class="layui-btn layui-btn-primary" type="button" id="searchButton">
                                <i class="fas fa-search"></i> 搜索
                            </button>
                            <button class="layui-btn layui-btn-normal" type="button" id="resetButton">
                                <i class="fas fa-undo"></i> 重置
                            </button>
                        </div>
                    </div>

                    <!-- 文档表格 -->
                    <div class="layui-table-responsive">
                        <table class="layui-table" id="documentsTable">
                            <thead>
                                <tr>
                                    <th width="50">
                                        <input type="checkbox" class="layui-form-checkbox" id="selectAll" lay-skin="primary">
                                    </th>
                                    <th>ID</th>
                                    <th>文件名</th>
                                    <th>文件类型</th>
                                    <th>文件大小</th>
                                    <th>上传时间</th>
                                    <th>状态</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody id="documentsTableBody">
                                <!-- 数据将通过JavaScript动态加载 -->
                            </tbody>
                        </table>
                    </div>

                    <!-- 分页 -->
                    <div id="pagination" class="layui-box layui-laypage layui-laypage-default"></div>

                    <!-- 状态信息 -->
                    <div style="margin-top: 20px;">
                        <span>共 <strong id="totalCount">0</strong> 个文档，已选择 <strong id="selectedCount">0</strong> 个</span>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 上传文档模态框 -->
<div id="uploadModal" style="display: none;">
    <div style="padding: 20px;">
        <form class="layui-form" id="uploadForm">
            <div class="layui-form-item">
                <label class="layui-form-label">选择文件</label>
                <div class="layui-input-block">
                    <input type="file" class="layui-input" id="fileInput" accept=".pdf,.docx,.xlsx,.txt,.md">
                    <div class="layui-form-mid layui-word-aux">支持 PDF、Word、Excel、TXT、Markdown 格式，最大 50MB</div>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">文档标题</label>
                <div class="layui-input-block">
                    <input type="text" class="layui-input" id="documentTitle" placeholder="请输入文档标题，留空则使用文件名">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">文档分类</label>
                <div class="layui-input-block">
                    <select class="layui-select" id="documentCategory">
                        <option value="">请选择分类</option>
                        <option value="1">技术文档</option>
                        <option value="2">产品文档</option>
                        <option value="3">用户手册</option>
                        <option value="4">其他</option>
                    </select>
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">描述</label>
                <div class="layui-input-block">
                    <textarea class="layui-textarea" id="documentDescription" placeholder="请输入文档描述..."></textarea>
                </div>
            </div>
        </form>
    </div>
</div>

<!-- 文档详情模态框 -->
<div id="documentDetailModal" style="display: none;">
    <div style="padding: 20px;">
        <div id="documentDetailContent">
            <!-- 文档详情将通过JavaScript动态加载 -->
        </div>
    </div>
</div>

@section Scripts {
    <script>
        let currentPage = 1;
        let pageSize = 10;
        let totalPages = 0;
        let documents = [];
        let selectedDocuments = [];

        // 页面加载完成后执行
        layui.use(['layer', 'element', 'form', 'laypage'], function(){
            var layer = layui.layer;
            var element = layui.element;
            var form = layui.form;
            var laypage = layui.laypage;
            
            console.log('Knowledge页面加载完成');
            console.log('API配置检查:', typeof ApiConfig !== 'undefined' ? '已加载' : '未加载');
            if (typeof ApiConfig !== 'undefined') {
                console.log('API基础URL:', ApiConfig.baseUrl);
                console.log('文档API基础URL:', ApiConfig.QaApi.baseUrl);
            }
            
            // 初始化页面
            loadDocuments();
            bindEvents();
            
            // 初始化分页
            initPagination();
        });

        // 绑定事件
        function bindEvents() {
            // 上传按钮
            $('#uploadButton').on('click', function() {
                console.log('上传按钮被点击');
                try {
                    openUploadModal();
                } catch (error) {
                    console.error('打开上传模态框失败:', error);
                    layui.use('layer', function(){
                        var layer = layui.layer;
                        layer.msg('打开上传模态框失败: ' + error.message, {icon: 2});
                    });
                }
            });
            
            // 刷新按钮
            $('#refreshButton').on('click', function() {
                console.log('刷新按钮被点击');
                loadDocuments();
            });
            
            // 批量删除按钮
            $('#batchDeleteButton').on('click', function() {
                console.log('批量删除按钮被点击');
                batchDeleteDocuments();
            });
            
            // 搜索按钮
            $('#searchButton').on('click', function() {
                console.log('搜索按钮被点击');
                searchDocuments();
            });
            
            // 重置按钮
            $('#resetButton').on('click', function() {
                console.log('重置按钮被点击');
                resetSearch();
            });
            
            // 全选/取消全选
            $('#selectAll').on('change', function() {
                const isChecked = $(this).prop('checked');
                $('.document-checkbox').prop('checked', isChecked);
                updateSelectedCount();
            });
            
            // 单个选择
            $(document).on('change', '.document-checkbox', function() {
                updateSelectedCount();
            });
        }

        // 加载文档列表
        function loadDocuments(page = 1) {
            currentPage = page;
            
            // 显示加载状态
            layui.use('layer', function(){
                var layer = layui.layer;
                const loadingIndex = layer.load(1, {shade: [0.1, '#fff']});
                
                // 从API获取文档列表
                const url = ApiConfig.getDocumentApiUrl('list', null, {
                    pageIndex: page,
                    pageSize: pageSize,
                    keyword: $('#searchInput').val().trim()
                });
                
                ApiConfig.get(url)
                    .then(function(response) {
                        layer.close(loadingIndex);
                        
                        if (response.success) {
                            documents = response.data || [];
                            const totalCount = response.totalCount || 0;
                            
                            // 渲染表格
                            renderDocumentsTable(documents);
                            
                            // 更新分页
                            updatePagination(totalCount);
                            
                            // 更新总数
                            $('#totalCount').text(totalCount);
                        } else {
                            layer.msg('加载文档列表失败: ' + (response.message || '未知错误'), {icon: 2});
                        }
                    })
                    .catch(function(error) {
                        layer.close(loadingIndex);
                        console.error('加载文档列表失败:', error);
                        layer.msg('网络错误，请检查连接后重试', {icon: 2});
                        
                        // 显示空数据
                        renderDocumentsTable([]);
                        $('#totalCount').text('0');
                    });
            });
        }

        // 渲染文档表格
        function renderDocumentsTable(documents) {
            const tbody = $('#documentsTableBody');
            tbody.empty();
            
            if (documents.length === 0) {
                tbody.append('<tr><td colspan="8" class="layui-text-center">暂无数据</td></tr>');
                return;
            }
            
            documents.forEach(function(doc) {
                const statusClass = getStatusClass(doc.status);
                const row = `
                    <tr>
                        <td>
                            <input type="checkbox" class="layui-form-checkbox document-checkbox" value="${doc.id}" lay-skin="primary">
                        </td>
                        <td>${doc.id}</td>
                        <td>${doc.title || doc.fileName || doc.name}</td>
                        <td>${doc.fileType || doc.type}</td>
                        <td>${doc.fileSizeFormatted || formatFileSize(doc.fileSize || doc.size)}</td>
                        <td>${formatDate(doc.createdAt || doc.uploadTime || doc.createTime)}</td>
                        <td><span class="layui-badge ${statusClass}">${getStatusText(doc.status)}</span></td>
                        <td>
                            <button class="layui-btn layui-btn-xs" onclick="viewDocument(${doc.id})">查看</button>
                            <button class="layui-btn layui-btn-normal layui-btn-xs" onclick="editDocument(${doc.id})">编辑</button>
                            <button class="layui-btn layui-btn-danger layui-btn-xs" onclick="deleteDocument(${doc.id})">删除</button>
                        </td>
                    </tr>
                `;
                tbody.append(row);
            });
            
            // 重新渲染表单元素
            layui.form.render('checkbox');
        }

        // 获取状态样式类
        function getStatusClass(status) {
            switch (status) {
                case 'Completed':
                case '已处理':
                    return 'layui-bg-green';
                case 'Processing':
                case '处理中':
                    return 'layui-bg-orange';
                case 'Pending':
                case '待处理':
                    return 'layui-bg-gray';
                case 'Failed':
                case '处理失败':
                    return 'layui-bg-red';
                default:
                    return 'layui-bg-gray';
            }
        }

        // 获取状态文本
        function getStatusText(status) {
            switch (status) {
                case 'Completed':
                    return '已完成';
                case 'Processing':
                    return '处理中';
                case 'Pending':
                    return '待处理';
                case 'Failed':
                    return '处理失败';
                default:
                    return status;
            }
        }

        // 格式化文件大小
        function formatFileSize(bytes) {
            if (!bytes || bytes === 0) return '0 B';
            if (bytes < 1024) return bytes + ' B';
            if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB';
            return (bytes / (1024 * 1024)).toFixed(1) + ' MB';
        }

        // 格式化日期
        function formatDate(dateString) {
            if (!dateString) return '';
            const date = new Date(dateString);
            return date.toLocaleString('zh-CN');
        }

        // 初始化分页
        function initPagination(totalCount) {
            layui.use('laypage', function(){
                var laypage = layui.laypage;
                
                laypage.render({
                    elem: 'pagination',
                    count: totalCount,
                    limit: pageSize,
                    curr: currentPage,
                    layout: ['count', 'prev', 'page', 'next', 'limit', 'skip'],
                    jump: function(obj, first) {
                        if (!first) {
                            loadDocuments(obj.curr);
                        }
                    }
                });
            });
        }

        // 更新分页
        function updatePagination(totalCount) {
            totalPages = Math.ceil(totalCount / pageSize);
            initPagination(totalCount);
        }

        // 更新选中数量
        function updateSelectedCount() {
            const selectedCount = $('.document-checkbox:checked').length;
            $('#selectedCount').text(selectedCount);
            
            // 更新批量删除按钮状态
            if (selectedCount > 0) {
                $('#batchDeleteButton').removeClass('layui-btn-disabled');
            } else {
                $('#batchDeleteButton').addClass('layui-btn-disabled');
            }
        }

        // 打开上传模态框
        function openUploadModal() {
            console.log('开始打开上传模态框');
            layui.use('layer', function(){
                var layer = layui.layer;
                console.log('Layui layer模块加载成功');
                
                try {
                    // 创建一个临时的HTML内容
                    const modalContent = `
                        <div style="padding: 20px;">
                            <form class="layui-form" id="uploadForm">
                                <div class="layui-form-item">
                                    <label class="layui-form-label">选择文件</label>
                                    <div class="layui-input-block">
                                        <input type="file" class="layui-input" id="fileInput" accept=".pdf,.docx,.xlsx,.txt,.md">
                                        <div class="layui-form-mid layui-word-aux">支持 PDF、Word、Excel、TXT、Markdown 格式，最大 50MB</div>
                                    </div>
                                </div>
                                <div class="layui-form-item">
                                    <label class="layui-form-label">文档标题</label>
                                    <div class="layui-input-block">
                                        <input type="text" class="layui-input" id="documentTitle" placeholder="请输入文档标题，留空则使用文件名">
                                    </div>
                                </div>
                                <div class="layui-form-item">
                                    <label class="layui-form-label">文档分类</label>
                                    <div class="layui-input-block">
                                        <select class="layui-select" id="documentCategory">
                                            <option value="">请选择分类</option>
                                            <option value="1">技术文档</option>
                                            <option value="2">产品文档</option>
                                            <option value="3">用户手册</option>
                                            <option value="4">其他</option>
                                        </select>
                                    </div>
                                </div>
                                <div class="layui-form-item">
                                    <label class="layui-form-label">描述</label>
                                    <div class="layui-input-block">
                                        <textarea class="layui-textarea" id="documentDescription" placeholder="请输入文档描述..."></textarea>
                                    </div>
                                </div>
                            </form>
                        </div>
                    `;
                    
                    layer.open({
                        type: 1,
                        title: '上传文档',
                        area: ['500px', '450px'],
                        content: modalContent,
                        btn: ['上传', '取消'],
                        shade: 0.3,
                        shadeClose: false,
                        yes: function(index) {
                            console.log('点击上传按钮');
                            uploadDocuments();
                            layer.close(index);
                        },
                        cancel: function(index) {
                            console.log('点击取消按钮');
                            layer.close(index);
                        },
                        success: function(layero, index) {
                            console.log('模态框打开成功，index:', index);
                            // 重新渲染表单元素
                            layui.form.render();
                            
                            // 添加文件选择事件监听器
                            setTimeout(function() {
                                const fileInput = layero.find('input[type="file"]')[0];
                                if (fileInput) {
                                    console.log('找到文件输入框，添加事件监听器');
                                    fileInput.addEventListener('change', function(e) {
                                        console.log('文件选择事件触发');
                                        console.log('选择的文件:', e.target.files);
                                        if (e.target.files.length > 0) {
                                            console.log('文件名称:', e.target.files[0].name);
                                            console.log('文件大小:', e.target.files[0].size);
                                        }
                                    });
                                } else {
                                    console.log('未找到文件输入框');
                                }
                            }, 100);
                        },
                        end: function() {
                            console.log('模态框关闭');
                        }
                    });
                } catch (error) {
                    console.error('打开模态框失败:', error);
                    layer.msg('打开模态框失败: ' + error.message, {icon: 2});
                }
            });
        }

        // 上传文档
        function uploadDocuments() {
            console.log('开始上传文档...');
            
            // 使用多种方式尝试获取文件输入框
            let fileInput = null;
            
            // // 方法1: 通过ID查找
            // fileInput = document.getElementById('fileInput');
            // console.log('方法1 - 通过ID查找:', fileInput);
            
            // // 方法2: 通过选择器查找
            // if (!fileInput) {
            //     fileInput = document.querySelector('input[type="file"]');
            //     console.log('方法2 - 通过选择器查找:', fileInput);
            // }
            
            // // 方法3: 通过Layui模态框内容查找
            // if (!fileInput) {
            //     const layerContent = document.querySelector('.layui-layer-content');
            //     if (layerContent) {
            //         fileInput = layerContent.querySelector('input[type="file"]');
            //         console.log('方法3 - 通过模态框内容查找:', fileInput);
            //     }
            // }
            
            // 方法4: 查找所有文件输入框
            if (!fileInput) {
                const allFileInputs = document.querySelectorAll('input[type="file"]');
                console.log('方法4 - 所有文件输入框:', allFileInputs);
                if (allFileInputs.length > 0) {
                    fileInput = allFileInputs[allFileInputs.length - 1]; // 取最后一个
                    console.log('使用最后一个文件输入框:', fileInput);
                }
            }
            
            if (!fileInput) {
                console.error('无法找到文件输入框');
                layui.use('layer', function(){
                    var layer = layui.layer;
                    layer.msg('无法找到文件输入框，请刷新页面重试', {icon: 2});
                });
                return;
            }
            
            const files = fileInput.files;
            console.log('文件输入框元素:', fileInput);
            console.log('文件输入框files属性:', files);
            console.log('文件数量:', files ? files.length : 0);
            
            if (!files || files.length === 0) {
                console.log('没有选择文件');
                layui.use('layer', function(){
                    var layer = layui.layer;
                    layer.msg('请选择要上传的文件', {icon: 2});
                });
                return;
            }
            
            console.log('文件名称:', files[0].name);
            console.log('文件大小:', files[0].size);
            console.log('文件类型:', files[0].type);
            
            const formData = new FormData();
            formData.append('file', files[0]); // 单个文件上传
            
            // 添加其他表单数据
            const titleInput = document.querySelector('#documentTitle') || document.querySelector('input[placeholder*="文档标题"]');
            const descriptionInput = document.querySelector('#documentDescription') || document.querySelector('textarea[placeholder*="文档描述"]');
            const categoryInput = document.querySelector('#documentCategory') || document.querySelector('select[id*="Category"]');
            
            const title = titleInput ? (titleInput.value || files[0].name) : files[0].name;
            const description = descriptionInput ? descriptionInput.value : '';
            const category = categoryInput ? categoryInput.value : '';
            
            console.log('文档标题:', title);
            console.log('文档描述:', description);
            console.log('文档分类:', category);
            
            formData.append('title', title);
            if (description) formData.append('description', description);
            if (category) formData.append('categoryId', category);
            
            layui.use('layer', function(){
                var layer = layui.layer;
                const loadingIndex = layer.load(1, {shade: [0.1, '#fff']});
                
                // 调用上传API
                const url = ApiConfig.getDocumentApiUrl('upload');
                console.log('上传API地址:', url);
                
                ApiConfig.upload(url, formData)
                    .then(function(response) {
                        layer.close(loadingIndex);
                        console.log('上传响应:', response);
                        
                        if (response.success) {
                            layer.msg('文档上传成功', {icon: 1});
                            loadDocuments(); // 重新加载数据
                        } else {
                            layer.msg('上传失败: ' + (response.message || '未知错误'), {icon: 2});
                        }
                    })
                    .catch(function(error) {
                        layer.close(loadingIndex);
                        console.error('上传失败:', error);
                        layer.msg('网络错误，请检查连接后重试', {icon: 2});
                    });
            });
        }

        // 添加测试数据 - 删除此函数，不再使用模拟数据
        // function addTestData() { ... }

        // 批量删除文档
        function batchDeleteDocuments() {
            const selectedIds = $('.document-checkbox:checked').map(function() {
                return $(this).val();
            }).get();
            
            if (selectedIds.length === 0) {
                layui.use('layer', function(){
                    var layer = layui.layer;
                    layer.msg('请选择要删除的文档', {icon: 2});
                });
                return;
            }
            
            layui.use('layer', function(){
                var layer = layui.layer;
                layer.confirm(`确定要删除选中的 ${selectedIds.length} 个文档吗？`, {icon: 3, title:'提示'}, function(index) {
                    layer.close(index);
                    
                    // 逐个删除选中的文档
                    let deletedCount = 0;
                    let totalCount = selectedIds.length;
                    
                    selectedIds.forEach(function(id) {
                        const url = ApiConfig.getDocumentApiUrl('delete', { id: id });
                        
                        ApiConfig.delete(url)
                            .then(function(response) {
                                deletedCount++;
                                if (deletedCount === totalCount) {
                                    layer.msg(`成功删除 ${deletedCount} 个文档`, {icon: 1});
                                    loadDocuments(); // 重新加载数据
                                }
                            })
                            .catch(function(error) {
                                deletedCount++;
                                console.error('删除文档失败:', error);
                                if (deletedCount === totalCount) {
                                    layer.msg(`删除完成，部分文档删除失败`, {icon: 2});
                                    loadDocuments(); // 重新加载数据
                                }
                            });
                    });
                });
            });
        }

        // 搜索文档
        function searchDocuments() {
            const searchTerm = $('#searchInput').val().trim();
            loadDocuments(1); // 重新加载第一页数据，包含搜索条件
        }

        // 重置搜索
        function resetSearch() {
            $('#searchInput').val('');
            loadDocuments(1);
        }

        // 查看文档
        function viewDocument(id) {
            // 调用获取文档详情API
            const url = ApiConfig.getDocumentApiUrl('detail', { id: id });
            
            ApiConfig.get(url)
                .then(function(response) {
                    if (response.success) {
                        const doc = response.data;
                        const detailHtml = `
                            <div class="layui-form">
                                <div class="layui-form-item">
                                    <label class="layui-form-label">文档标题</label>
                                    <div class="layui-input-block">
                                        <div class="layui-form-mid">${doc.title || '无标题'}</div>
                                    </div>
                                </div>
                                <div class="layui-form-item">
                                    <label class="layui-form-label">文件类型</label>
                                    <div class="layui-input-block">
                                        <div class="layui-form-mid">${doc.fileType || '未知'}</div>
                                    </div>
                                </div>
                                <div class="layui-form-item">
                                    <label class="layui-form-label">文件大小</label>
                                    <div class="layui-input-block">
                                        <div class="layui-form-mid">${doc.fileSizeFormatted || formatFileSize(doc.fileSize)}</div>
                                    </div>
                                </div>
                                <div class="layui-form-item">
                                    <label class="layui-form-label">创建时间</label>
                                    <div class="layui-input-block">
                                        <div class="layui-form-mid">${formatDate(doc.createdAt)}</div>
                                    </div>
                                </div>
                                <div class="layui-form-item">
                                    <label class="layui-form-label">状态</label>
                                    <div class="layui-input-block">
                                        <span class="layui-badge ${getStatusClass(doc.status)}">${getStatusText(doc.status)}</span>
                                    </div>
                                </div>
                                <div class="layui-form-item">
                                    <label class="layui-form-label">描述</label>
                                    <div class="layui-input-block">
                                        <div class="layui-form-mid">${doc.description || '无描述'}</div>
                                    </div>
                                </div>
                                <div class="layui-form-item">
                                    <label class="layui-form-label">标签</label>
                                    <div class="layui-input-block">
                                        <div class="layui-form-mid">${doc.tags ? doc.tags.join(', ') : '无标签'}</div>
                                    </div>
                                </div>
                            </div>
                        `;
                        
                        $('#documentDetailContent').html(detailHtml);
                        
                        layui.use('layer', function(){
                            var layer = layui.layer;
                            layer.open({
                                type: 1,
                                title: '文档详情',
                                area: ['600px', '500px'],
                                content: $('#documentDetailModal'),
                                shade: 0.3, // 设置遮罩透明度
                                shadeClose: false // 点击遮罩不关闭
                            });
                        });
                    } else {
                        layui.use('layer', function(){
                            var layer = layui.layer;
                            layer.msg('获取文档详情失败: ' + (response.message || '未知错误'), {icon: 2});
                        });
                    }
                })
                .catch(function(error) {
                    console.error('获取文档详情失败:', error);
                    layui.use('layer', function(){
                        var layer = layui.layer;
                        layer.msg('网络错误，请检查连接后重试', {icon: 2});
                    });
                });
        }

        // 编辑文档
        function editDocument(id) {
            layui.use('layer', function(){
                var layer = layui.layer;
                layer.msg('编辑功能开发中...', {icon: 16});
            });
        }

        // 删除文档
        function deleteDocument(id) {
            layui.use('layer', function(){
                var layer = layui.layer;
                layer.confirm('确定要删除这个文档吗？', {icon: 3, title:'提示'}, function(index) {
                    layer.close(index);
                    
                    // 调用删除API
                    const url = ApiConfig.getDocumentApiUrl('delete', { id: id });
                    
                    ApiConfig.delete(url)
                        .then(function(response) {
                            if (response.success) {
                                layer.msg('删除成功', {icon: 1});
                                loadDocuments(); // 重新加载数据
                            } else {
                                layer.msg('删除失败: ' + (response.message || '未知错误'), {icon: 2});
                            }
                        })
                        .catch(function(error) {
                            console.error('删除失败:', error);
                            layer.msg('网络错误，请检查连接后重试', {icon: 2});
                        });
                });
            });
        }
    </script>
} 